package com.freak.kotlinfitnessserver.activity.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.freak.kotlinfitnessserver.activity.fragment.viewmodel.FeaturesViewModel
import com.freak.kotlinfitnessserver.app.App
import com.freak.kotlinfitnessserver.constant.ByteConstant
import com.freak.kotlinfitnessserver.constant.DeviceConstant
import com.freak.kotlinfitnessserver.databinding.FragmentFitnessMachineFeaturesBinding
import com.freak.kotlinfitnessserver.room.FeaturesData
import com.freak.kotlinfitnessserver.util.LogUtil
import com.freak.kotlinfitnessserver.util.ToastUtil
import kotlinx.coroutines.launch

class FitnessMachineFeaturesFragment : Fragment() {
    private lateinit var binding: FragmentFitnessMachineFeaturesBinding

    private lateinit var deviceType: String

    private val featuresViewModel: FeaturesViewModel by activityViewModels {
        FeaturesViewModel.FeaturesViewModelFactory((activity?.application as App).fitnessDeviceDatabase.featuresDataDao())
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentFitnessMachineFeaturesBinding.inflate(inflater, container, false)
        initClickListener()
        initData()
        return binding.root
    }

    private fun initData() {
        arguments ?: let {
            return
        }
        deviceType = requireArguments().getString(DeviceConstant.deviceType, "")
        lifecycleScope.launch {
            val featuresData = featuresViewModel.getFeaturesData(deviceType)
            featuresData ?: let {
                return@launch
            }
            val flag = featuresData.fitnessMachineFeaturesFlag
            LogUtil.i(TAG, "flag = $flag")
            updateFitnessMachineFeatures(flag)
        }
    }

    private fun updateFitnessMachineFeatures(flag: Int) {
        binding.checkBoxAverageSpeedSupported.isChecked =
            flag and ByteConstant.BYTE_0X01 != 0
        binding.checkBoxCadenceSupported.isChecked =
            flag and ByteConstant.BYTE_0X02 != 0
        binding.checkBoxTotalDistanceSupported.isChecked =
            flag and ByteConstant.BYTE_0X04 != 0
        binding.checkBoxInclinationSupported.isChecked =
            flag and ByteConstant.BYTE_0X08 != 0
        binding.checkBoxElevationGainSupported.isChecked =
            flag and ByteConstant.BYTE_0X10 != 0
        binding.checkBoxPaceSupported.isChecked =
            flag and ByteConstant.BYTE_0X20 != 0
        binding.checkBoxStepCountSupported.isChecked =
            flag and ByteConstant.BYTE_0X40 != 0
        binding.checkBoxResistanceLevelSupported.isChecked =
            flag and ByteConstant.BYTE_0X80 != 0
        binding.checkBoxStrideCountSupported.isChecked =
            flag and ByteConstant.BYTE_0x100 != 0
        binding.checkBoxExpendedEnergySupported.isChecked =
            flag and ByteConstant.BYTE_0x200 != 0
        binding.checkBoxHeartRateMeasurementSupported.isChecked =
            flag and ByteConstant.BYTE_0x400 != 0
        binding.checkBoxMetabolicEquivalentSupported.isChecked =
            flag and ByteConstant.BYTE_0x800 != 0
        binding.checkBoxElapsedTimeSupported.isChecked =
            flag and ByteConstant.BYTE_0x1000 != 0
        binding.checkBoxRemainingTimeSupported.isChecked =
            flag and ByteConstant.BYTE_0x2000 != 0
        binding.checkBoxPowerMeasurementSupported.isChecked =
            flag and ByteConstant.BYTE_0x4000 != 0
        binding.checkBoxForceOnBeltAndPowerOutputSupported.isChecked =
            flag and ByteConstant.BYTE_0x8000 != 0
        binding.checkBoxUserDataRetentionSupported.isChecked =
            flag and ByteConstant.BYTE_0x10000 != 0
    }

    private fun initClickListener() {
        binding.buttonSaveFitnessMachine.setOnClickListener {
            var flag = ByteConstant.BYTE_0X00
            if (binding.checkBoxAverageSpeedSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0X01
            }
            if (binding.checkBoxCadenceSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0X02
            }
            if (binding.checkBoxTotalDistanceSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0X04
            }
            if (binding.checkBoxInclinationSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0X08
            }
            if (binding.checkBoxElevationGainSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0X10
            }
            if (binding.checkBoxPaceSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0X20
            }
            if (binding.checkBoxStepCountSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0X40
            }
            if (binding.checkBoxResistanceLevelSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0X80
            }
            if (binding.checkBoxStrideCountSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0x100
            }
            if (binding.checkBoxExpendedEnergySupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0x200
            }
            if (binding.checkBoxHeartRateMeasurementSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0x400
            }
            if (binding.checkBoxMetabolicEquivalentSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0x800
            }
            if (binding.checkBoxElapsedTimeSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0x1000
            }
            if (binding.checkBoxRemainingTimeSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0x2000
            }
            if (binding.checkBoxPowerMeasurementSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0x4000
            }
            if (binding.checkBoxForceOnBeltAndPowerOutputSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0x8000
            }
            if (binding.checkBoxUserDataRetentionSupported.isChecked) {
                flag = flag xor ByteConstant.BYTE_0x10000
            }
            if (flag == 0) {
                ToastUtil.toastShort("请选择支持的能力")
                return@setOnClickListener
            }
            lifecycleScope.launch {
                val featuresData = featuresViewModel.getFeaturesData(deviceType)
                // 保存到数据库
                featuresData ?: let {
                    val insertFeaturesData = FeaturesData(
                        deviceType = deviceType,
                        fitnessMachineFeaturesFlag = flag,
                        targetSettingFeaturesFlag = 0
                    )
                    featuresViewModel.insertFeaturesData(insertFeaturesData)
                    return@launch
                }
                val updateFeaturesData = FeaturesData(
                    id = featuresData.id,
                    deviceType = featuresData.deviceType,
                    fitnessMachineFeaturesFlag = flag,
                    targetSettingFeaturesFlag = featuresData.targetSettingFeaturesFlag
                )
                featuresViewModel.updateFeaturesData(updateFeaturesData)
                initData()
            }
        }
    }


    companion object {
        const val TAG: String = "FitnessMachineFeaturesFragment"

        @JvmStatic
        fun newInstance(deviceType: String) = FitnessMachineFeaturesFragment().apply {
            arguments = Bundle().apply {
                putString(DeviceConstant.deviceType, deviceType)
            }
        }
    }
}